import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    Chip,
    Divider,
    FormControl,
    IconButton,
    InputLabel,
    MenuItem,
    Paper,
    Select,
    Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow, Typography
} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";

import {list as listTeacher} from "../../api/info/teacher";
import {children as getChildren, list as listStudent} from "../../api/school/student";

import {scheduleList} from "../../api/lesson/lesson-schedule";
import RefreshIcon from '@mui/icons-material/Refresh';
import SearchIcon from '@mui/icons-material/Search';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import ExpandIcon from '@mui/icons-material/Expand';
import CompressIcon from '@mui/icons-material/Compress';

import {RestartAlt} from "@mui/icons-material";

import LoadingButton from "@mui/lab/LoadingButton";
import {useSelector} from "react-redux";

const defaultForm = {
    teacherId: 0,
    studentId: 0,
};
Object.freeze(defaultForm);

function ScheduleList() {

    const user = useSelector(state => state.auth.user);

    const [principal, setPrincipal] = useState(false);
    const [parent, setParent] = useState(false);
    const [teacher, setTeacher] = useState(false);

    const [queryEnabled, setQueryEnabled] = useState(false);

    const [form, setForm] = useState({...defaultForm});

    const [loading, setLoading] = useState(false);

    const [schedules, setSchedules] = useState([]);
    const [teachers, setTeachers] = useState([]);
    const [students, setStudents] = useState([]);
    const [children, setChildren] = useState([]);

    const [searching, setSearching] = useState(false);
    const [showForm, setShowForm] = useState(true);
    const [dense, setDense] = useState(false);

    function loadSchedules(query) {
        setLoading(true);

        scheduleList(query).then(data => {
            setSchedules(data);
            setLoading(false);
            setSearching(false);
        });
    }

    function loadTeacher() {
        listTeacher().then(data => {
            setTeachers(data);
        });
    }

    function loadStudent() {
        listStudent().then(data => {
            setStudents(data || []);
        });
    }

    function loadChildren() {
        getChildren().then(data => {
            setChildren(data);
            setQueryEnabled(data.length > 0);
        });
    }

    useEffect(() => {
        loadSchedules(defaultForm);
    }, []);

    useEffect(() => {
        const _principal = user.role === 'PRINCIPAL';
        const _parent = user.role === 'PARENT';
        const _teacher = user.role === 'TEACHER';

        setPrincipal(_principal);
        setParent(_parent);
        setTeacher(_teacher);

        setQueryEnabled(_principal);

        if (_principal) {
            loadTeacher();
            loadStudent();
        } else if (_parent) {
            loadChildren();
        }
    }, [user.role]);

    function handleChange(event) {
        const {name, value} = event.target;
        setForm({...form, [name]: value});
    }

    const now = new Date();

    function beforeNow(schedule) {
        return new Date(schedule.lessonTime) < now;
    }

    return (
        <Box p={4} display="flex" gap={4} flexDirection="column">
            <Card raised sx={{padding: 2, boxSizing: 'border-box', width: '100%'}}>
                <CardHeader
                    title={
                        <Stack direction="row" alignItems="center" spacing={1}>
                            <Typography variant="h5">课程表</Typography>
                            {loading && <CircularProgress color="inherit" size={24}/>}
                        </Stack>}
                    action={
                        <Box mr={1}>
                            {queryEnabled && <IconButton onClick={() => setShowForm(!showForm)}>
                                {showForm ? <VisibilityOffIcon/> : <VisibilityIcon/>}
                            </IconButton>}

                            <IconButton onClick={() => setDense(!dense)}>
                                {dense ? <ExpandIcon/> : <CompressIcon/>}
                            </IconButton>

                            <IconButton onClick={() => loadSchedules(form)}><RefreshIcon/></IconButton>
                        </Box>
                    }/>

                <CardContent>
                    {queryEnabled && showForm && <Box mb={4} display="flex" gap={2} alignItems="center" flexWrap="wrap">
                        {principal && <FormControl sx={{width: 180}} size="small">
                            <InputLabel>授课老师</InputLabel>
                            <Select value={form.teacherId} label="授课老师" name="teacherId" onChange={handleChange}>
                                <MenuItem value="0">选择授课老师</MenuItem>
                                <Divider/>
                                {teachers.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                            </Select>
                        </FormControl>}

                        {principal && <FormControl sx={{width: 180}} size="small">
                            <InputLabel>学员</InputLabel>
                            <Select value={form.studentId} label="学员" name="studentId" onChange={handleChange}>
                                <MenuItem value="0">选择学员</MenuItem>
                                <Divider/>
                                {students.filter(e => e.role === 'PARENT').map(e =>
                                    <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                                <Divider/>
                                {students.filter(e => e.role === 'STUDENT').map(e =>
                                    <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                            </Select>
                        </FormControl>}

                        {parent && children.length > 0 && <FormControl sx={{width: 180}} size="small">
                            <InputLabel>学员</InputLabel>
                            <Select value={form.studentId} label="学员" name="studentId" onChange={handleChange}>
                                <MenuItem value="0">选择学员</MenuItem>
                                <Divider/>
                                <MenuItem value={user.id}>{user.name}（自己）</MenuItem>
                                <Divider/>
                                {children.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                            </Select>
                        </FormControl>}

                        <Button startIcon={<RestartAlt/>} variant="contained" color="primary"
                                onClick={() => setForm({...defaultForm})}>
                            重置
                        </Button>
                        <LoadingButton startIcon={<SearchIcon/>} variant="contained" color="primary"
                                       type="submit" loading={searching}
                                       loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                       onClick={() => {
                                           setSearching(true);
                                           loadSchedules(form);
                                       }}>查询</LoadingButton>
                    </Box>}

                    <TableContainer component={Paper}>
                        <Table size={dense ? 'small' : 'medium'}>
                            <TableHead>
                                <TableRow>
                                    <TableCell width={'30px'}>ID</TableCell>
                                    <TableCell width={'160px'}>课程</TableCell>
                                    <TableCell width={'160px'}>班级</TableCell>
                                    {!teacher && <TableCell width={'100px'}>教师</TableCell>}
                                    <TableCell>学员</TableCell>
                                    <TableCell align={"center"} width={'90px'}>第几课</TableCell>
                                    <TableCell width={'160px'} align={"center"}>时间</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {schedules.map(e => (
                                    <TableRow key={e.id}
                                              sx={{
                                                  backgroundColor: beforeNow(e) ? '#e1bee7' : 'inherit'
                                              }}>
                                        <TableCell component="th" scope="row">{e.id}</TableCell>
                                        <TableCell>{e.course.name}</TableCell>
                                        <TableCell>{e.classGroup.name}</TableCell>
                                        {!teacher && <TableCell>{e.teacher.name}</TableCell>}
                                        <TableCell><Stack direction="row" spacing={1}>
                                            {e.students.map(s =>
                                                <Chip color={s.id === user.id ? 'primary' :
                                                    (s.id === form.studentId ? 'secondary' : 'default')}
                                                      variant="outlined" size="small" key={s.id} label={s.name}/>
                                            )}
                                        </Stack></TableCell>
                                        <TableCell
                                            sx={{color: e.lessonNumber === e.course.lessonCount ? '#ff9800' : 'inherit'}}
                                            align={"center"}>{e.lessonNumber}/{e.course.lessonCount}</TableCell>
                                        <TableCell align={"center"}>{e.lessonTime}</TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                </CardContent>
            </Card>
        </Box>
    );
}

export default ScheduleList;
